import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, Space, Modal } from 'antd'
import { UpOutlined, DownOutlined, DownloadOutlined } from '@ant-design/icons'
// import moment from 'moment'
import _ from 'loadsh'
import { addWindow } from '@redux/actions'
import style from '../filingCaseManage/CaseManage.module.less'
import Text from '@src/components/Text'
import { compress, compressLicenseAndMobile, confirmAction, decomporessListLicenseAndMobileAndBank } from '@src/assets/js/tool'
import { json2Excel } from '@src/assets/js/excel'

const { Item } = Form
const layout = {
  labelCol: { flex: '80px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      width: 100
    },
    {
      title: '身份证',
      dataIndex: 'license',
      key: 'license',
      width: 100
    },
    {
      title: '开户行',
      dataIndex: 'bank',
      key: 'bank',
      width: 150
    },
    {
      title: '银行卡',
      dataIndex: 'bank_accountno',
      key: 'bank_accountno',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 60,
      render: (value, line) => {
        return <span className={style['link-btn']} onClick={() => this.modifyDetail(line)}>修改</span>
      }
    }
  ]
}

class ArbitratorList extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    detailData: null,
    detailVisible: false
  }

  formRef = React.createRef()

  detailFormRef = React.createRef()

  searchHandle (d) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData(d)
    })
  }

  // 获取查询参数
  getParams (form) {
    form = form || this.formRef.current.getFieldsValue()
    const condition = []
    if (form.name !== undefined && form.name !== '') {
      condition.push({ k: 'name', o: 'like', v: `%${form.name}%` })
    }
    const data = {
      condition: JSON.stringify(condition)
    }
    return data
  }

  // 获取仲裁员数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination } = this.state
    const { current, pageSize } = pagination
    this.setState({ loading: true })
    const d = this.getParams(form)
    d.current = current
    d.page_size = pageSize
    this.$get('/api/xapc/arbitrator', d).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        decomporessListLicenseAndMobileAndBank(res.data.list)
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle (callback = () => {}) {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 设置要修改的仲裁员详情
  modifyDetail (l) {
    l = _.cloneDeep(l)
    this.setState({
      detailData: l,
      detailVisible: true
    }, () => {
      setTimeout(() => {
        l.professional = l.professional ? l.professional.split(',') : []
        l.cause_action = l.cause_action ? l.cause_action.split(',') : []
        const keys = Object.keys(l)
        keys.forEach(key => {
          if (l[key] === null) {
            l[key] = undefined
          }
        })
        this.detailFormRef.current.setFieldsValue(l)
      }, 100)
    })
  }

  // 更新仲裁员详情
  updateDetail (d) {
    const hide = message.loading('更新中', 120)
    compressLicenseAndMobile(d)
    if (typeof d.bank_accountno === 'string' && d.bank_accountno.length > 0) {
      d.bank_accountno = compress(d.bank_accountno)
    }
    this.$put(`/api/xapc/arbitrator/${d.id}`, d)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.setState({
            detailData: null,
            detailVisible: false
          }, () => {
            this.getTableData()
          })
        } else {
          message.warning(res.message)
        }
      })
      .catch(() => hide())
  }

  downloadExcel (form) {
    form = form || this.formRef.current.getFieldsValue()
    const hide = message.loading('导出中', 120)
    const d = this.getParams(form)
    d.current = 1
    d.page_size = 1000000
    this.$get('/api/xapc/arbitrator', d).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        hide()
        decomporessListLicenseAndMobileAndBank(res.data.list)
        const list = res.data.list.map((l, i) => {
          return {
            序号: i + 1,
            姓名: l.name,
            开户行: l.bank,
            银行卡号: l.bank_accountno,
            身份证: l.license,
            手机号: l.mobile
          }
        })
        json2Excel([{ data: list, sheetname: '财务仲裁员列表' }], '财务仲裁员列表')
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  componentDidUpdate (prev) {

  }

  componentDidMount () {
    this.getTableData()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  renderModal () {
    return (
      <Modal
        title='修改仲裁员'
        destroyOnClose
        open={this.state.detailVisible}
        onOk={() => this.detailFormRef.current.submit()}
        onCancel={() => this.setState({ detailVisible: false, detailData: null })}
        okText='确定'
        cancelText='取消'
        forceRender
      >
        <Form ref={this.detailFormRef} labelCol={{ flex: '108px' }} name='arbitrator-detail' onFinish={d => this.updateDetail(d)}>
          <Item noStyle name='id'><span /></Item>
          <Item name='name' label='名称'>
            <Text />
          </Item>
          <Item name='license' label='身份证'>
            <Input placeholder='请输入' />
          </Item>
          <Item name='bank' label='开户行'>
            <Input placeholder='请输入' />
          </Item>
          <Item name='bank_accountno' label='银行账户'>
            <Input placeholder='请输入' />
          </Item>
        </Form>
      </Modal>
    )
  }

  render () {
    const columns = getColumns.call(this)
    const initialValues = {}
    return (
      <div className={style.container}>
        {this.renderModal()}
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} initialValues={initialValues} ref={this.formRef} onFinish={v => this.searchHandle(v)}>
              <Row>
                <Col span={8}>
                  <Item label='名称' name='name'>
                    <Input placeholder='请输入' />
                  </Item>
                </Col>
                <Col span={16} />
              </Row>
              <Row gutter={24}>
                <Item className={style['right-line']}>
                  <Space size='middle'>
                    <Button type='primary' ghost htmlType='submit'>搜索</Button>
                    <Button htmlType='reset' onClick={() => this.resetHandle()}>重置</Button>
                  </Space>
                </Item>
              </Row>
            </Form>
          </div>
        </div>

        <div className={style['table-container']}>
          <div style={{ marginBottom: '12px' }}>
            <Button type='primary' ghost onClick={() => confirmAction('您确定要导出excel吗？', () => { this.downloadExcel() })} icon={<DownloadOutlined />}>导出excel</Button>
          </div>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={v => this.tableChange(v)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(ArbitratorList)
